package ldh.im.monitor.controller.sub;

import com.google.common.eventbus.Subscribe;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import ldh.im.dto.business.monitor.MonitorActiveUserInfo;
import ldh.im.fxbase.util.FxThreadUtil;
import ldh.im.fxbase.util.RpcUtil;
import ldh.im.monitor.cell.MonitorUserCell;
import ldh.im.monitor.event.MonitorActiveUserCollection;
import ldh.im.monitor.util.Param;
import ldh.rpc.cache.CacheService;
import org.controlsfx.control.GridView;

import java.net.URL;
import java.util.*;

public class UserController implements Initializable {

    private @FXML GridView<MonitorActiveUserInfo> userGridView;

    private ObservableList<MonitorActiveUserInfo> monitorActiveUserInfoObservableList = FXCollections.observableArrayList();

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        userGridView.setItems(monitorActiveUserInfoObservableList);

        userGridView.setCellHeight(150d);
        userGridView.setCellWidth(150d);

        userGridView.setCellFactory(gridView-> new MonitorUserCell());

        CacheService cacheService = RpcUtil.getRpcBootstrap().getRpcConfig().getCacheService();
        Set<MonitorActiveUserInfo> monitorActiveUserInfoList = (Set<MonitorActiveUserInfo>) cacheService.getCache(Param.CACHE_USER_LIST);
        if (monitorActiveUserInfoList != null) {
            show(monitorActiveUserInfoList);
        }
    }

    @Subscribe
    public synchronized void userInfo(MonitorActiveUserInfo monitorActiveUserInfo) {
        show(monitorActiveUserInfo);
    }

    @Subscribe
    public synchronized void userInfoList(MonitorActiveUserCollection monitorActiveUserList) {
        show(monitorActiveUserList.getMonitorActiveUserInfoSet());
    }

    private void show(MonitorActiveUserInfo monitorActiveUserInfo) {
        FxThreadUtil.runLater(()->{
            if (!monitorActiveUserInfoObservableList.contains(monitorActiveUserInfo)) {
                monitorActiveUserInfoObservableList.add(monitorActiveUserInfo);
            }
        });
    }

    private void show(Collection<MonitorActiveUserInfo> monitorActiveUserInfos) {
        FxThreadUtil.runLater(()->monitorActiveUserInfos.forEach(monitorActiveUserInfo -> {
            if (!monitorActiveUserInfoObservableList.contains(monitorActiveUserInfo)) {
                monitorActiveUserInfoObservableList.add(monitorActiveUserInfo);
            }
        }));
    }
}
